package com.edu.lxshpc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.edu.lxshpc.pojo.Blog;
import com.edu.lxshpc.pojo.BlogCategory;
import com.edu.lxshpc.pojo.User;
import com.edu.lxshpc.povo.BlogCommentVO;
import com.edu.lxshpc.povo.BlogVO;
import com.edu.lxshpc.povo.UserVO;
import com.edu.lxshpc.service.BlogCommentService;
import com.edu.lxshpc.service.BlogService;
import com.edu.lxshpc.mapper.BlogMapper;
import com.edu.lxshpc.utils.MyException;
import com.edu.lxshpc.utils.PageParams;
import com.edu.lxshpc.utils.PageResult;
import com.edu.lxshpc.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.edu.lxshpc.utils.RedisStatic.BLOG_ARTICLE_ID_KEY;
import static com.edu.lxshpc.utils.RedisStatic.EXPIRE;


/**
* @author Sanshan
* @description 针对表【blog】的数据库操作Service实现
* @createDate 2023-11-09 10:05:42
*/
@Service
@Transactional
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog>
    implements BlogService{
    @Autowired
    private BlogMapper blogMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private BlogCommentService blogCommentService;

    /**
     * 获得博客分页列表
     *
     * @param pageParams 分页参数
     * @param userId     用户id
     * @param categoryId 分类id
     * @param search     搜索关键字
     * @return 业务结果
     */
    @Override
    public Result getArticleList(PageParams pageParams, Long userId, Integer categoryId, String search) {
        QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();
        // 用户id不等于空
        if (userId != null){
            queryWrapper.eq("user_id",userId);
        }
        if(categoryId != null && categoryId > 0) {
            queryWrapper.eq("category_id",categoryId);
        }
        if(search!= null && search.length() > 0){
            queryWrapper.like("title",search);
        }
        // 查询到blog集合
        Page<Blog> blogPage = blogMapper.selectPage(new Page<>(pageParams.getPage(), pageParams.getPageSize(),true), queryWrapper);
        if(blogPage.getRecords().size() == 0){
            return  new Result(0,"无数据",new PageResult<Blog>());
        }
        // 属性复制
        List<Long> userIds = blogPage.getRecords().stream().map(item -> item.getUserId()).collect(Collectors.toList());
        List<Integer> categoryIds = blogPage.getRecords().stream().map(item -> item.getCategoryId()).collect(Collectors.toList());
        // 获得博客用户信息
        List<User> userList = Db.lambdaQuery(User.class)
                .select(User::getId,User::getUsername,User::getNickname,User::getAvatar)
                .in(User::getId, userIds)
                .list();
        List<UserVO> userVOS = BeanUtil.copyToList(userList, UserVO.class);
        // 获得博客分类信息
        List<BlogCategory> blogCategoryList = Db.lambdaQuery(BlogCategory.class).in(BlogCategory::getCategoryId, categoryIds).list();
        if (CollUtil.isEmpty(userList) && CollUtil.isEmpty(blogCategoryList)){
            throw new MyException("查询失败");
        }
        blogPage.getRecords().forEach(item ->{
            item.setUser(userVOS.stream().filter(user -> user.getId().equals(item.getUserId())).findFirst().get());
            item.setBlogCategory(blogCategoryList.stream().filter(blogCategory -> blogCategory.getCategoryId().equals(item.getCategoryId())).findFirst().get());
        });
        List<BlogVO> blogVOS = BeanUtil.copyToList(blogPage.getRecords(), BlogVO.class);
        PageResult<BlogVO> pageResult = new PageResult<>(
                blogVOS,blogPage.getTotal(),blogPage.getCurrent(),blogPage.getPages(),blogPage.getSize());
        return Result.success(pageResult);
    }
    /**
     * 获取文章详情
     * @param blogId 文章Id
     * @return Result对象，包含文章详情或错误信息
     */
    @Override
    public Result getBlogDetail(Long blogId) {
        String key = BLOG_ARTICLE_ID_KEY + blogId;
        // redis缓存，缓存不存在，查数据库
        if(Boolean.TRUE.equals(stringRedisTemplate.hasKey(key))){
            String jsonStr = stringRedisTemplate.opsForValue().get(key);
            Blog blog = JSONUtil.toBean(jsonStr,Blog.class);
            return Result.success(blog);
        }
        // 从数据库查询
        Blog blog = blogMapper.selectOne(new QueryWrapper<Blog>().eq("blog_id",blogId));
        BlogVO blogVO = BeanUtil.copyProperties(blog, BlogVO.class);
        User one = Db.lambdaQuery(User.class).eq(User::getId, blog.getUserId()).one();
        UserVO userVO = null;
        if(one != null){
            userVO  = BeanUtil.copyProperties(one, UserVO.class);
        }
        blogVO.setUser(userVO);
        BlogCategory category = Db.lambdaQuery(BlogCategory.class).eq(BlogCategory::getCategoryId, blog.getCategoryId()).one();
        if(category != null){
            blogVO.setBlogCategory(category);
        }
        String jsonStr = JSONUtil.toJsonStr(blogVO);
        stringRedisTemplate.opsForValue().set(key,jsonStr,EXPIRE, TimeUnit.MINUTES);
        return Result.success(blogVO);
    }
    /**
     * 获取博客评论列表

     * @param pageParams 分页参数
     * @param blogId     博客id
     * @return Result<List < BookCommentVO>>
     */
    @Override
    public Result getBlogComments(Long blogId, PageParams pageParams ) {
        if(BeanUtil.isEmpty(pageParams)){
            return blogCommentService.getBlogComments(blogId);
        }
        return blogCommentService.getBlogComments(blogId,pageParams);
    }
    /**
     *  * 插入评论
     * @param blogCommentVO 评论vo类
     * @return 业务信息
     */
    @Override
    public Result saveBlogComment(BlogCommentVO blogCommentVO) {
        return blogCommentService.saveBlogComment(blogCommentVO);
    }
    /**
     * 删除博客
     * @param blogId 博客id
     * @return 业务结果信息
     */
    @Override
    public Result removeById(Long blogId) {
        QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("blog_id",blogId);
        Blog blog = blogMapper.selectOne(queryWrapper);
        if(blog == null){
            return Result.fail("文章不存在");
        }
        int i = blogMapper.delete(queryWrapper);
        return i > 0? Result.success("删除成功") : Result.fail("删除失败");
    }

    @Override
    public Result saveOrUpdateBlog(BlogVO blogVO) {
        Blog blog = BeanUtil.copyProperties(blogVO, Blog.class);
        String key = BLOG_ARTICLE_ID_KEY + blogVO.getBlogId();
        boolean b = this.saveOrUpdate(blog);
        if(!b){
            return Result.fail("插入（更新）失败");
        }
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(blogVO),EXPIRE, TimeUnit.MINUTES);
        return Result.success("插入（更新）成功");
    }
    /**
     * 获得博客标题列表
     * @return 业务结果信息
     */
    @Override
    public Result getBlogTitleList() {
        QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("blog_id","title");
        List<Blog> blogs = blogMapper.selectList(queryWrapper);
        return Result.success(blogs);
    }
    /**
     * 删除评论
     * @param commentId 评论id
     * @return 业务结果信息
     */
    @Override
    public Result removeCommentById(Long commentId) {
        return blogCommentService.removeCommentById(commentId);
    }

}




